package utils

import (
	"fmt"
	deploy "gingorm/proto/common"
	"github.com/golang/protobuf/proto"
	"gorm.io/driver/mysql"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"io/ioutil"
	"os"
	"strings"
	"time"
)

func LoadProtoMessage(filePath string , message proto.Message) error {
	file, err := ioutil.ReadFile(filePath)
	if err != nil {
		return err
	}
	err = proto.UnmarshalText(string(file), message)
	if err != nil {
		return  err
	}
	return nil
}

func RecordPid(procName string){
	// 获取pid
	pid := os.Getpid()
	err := ioutil.WriteFile(fmt.Sprintf("%v.pid", procName), []byte(fmt.Sprintf("%d", pid)), os.ModePerm)
	if err != nil {
		panic(err)
	}
}


func InstanceDB(SqlType string, DataBaseInfo *deploy.DataBaseInfo, Config gorm.Config)(error, *gorm.DB){
	SqlType = strings.ToLower(SqlType)
	var dialector gorm.Dialector
	switch SqlType {
	case "mysql":
		dialector = mysql.Open(DataBaseInfo.GetDsn())
	case "postgresql":
		dialector = postgres.Open(DataBaseInfo.GetDsn())
	default:
		return fmt.Errorf("sorry! we haven't driver to surport your Databases %s", SqlType), nil
	}

	databse, err := gorm.Open(dialector, &Config)
	if err != nil {
		return fmt.Errorf("Link %v database failed err:%v ", SqlType ,err) , nil
	}
	db, err := databse.DB()
	if err != nil {
		return fmt.Errorf("init %v db error:%v",SqlType, err), nil
	}
	db.SetMaxIdleConns(int(DataBaseInfo.GetMaxIdleConns()))// 最大空闲连接数， 默认情况是2个，
	db.SetMaxOpenConns(int(DataBaseInfo.GetMaxOpenConns()))// 最大连接数，默认情况是无限，由于数据库本身瓶颈，无限创建会损耗性能能。
	db.SetConnMaxLifetime(time.Duration(DataBaseInfo.GetConnMaxLifetime()) * time.Second)

	return nil , databse
}